package com.hup.utils.commons.start;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;

import java.util.ArrayList;
import java.util.Iterator;

/**
 * https://blog.csdn.net/dadiyang/article/details/90349793
 * @deprecated 原来用于app启动时记录进度,目前留着用于提供Appender的使用参考
 * @author hugan
 * @date 2019/8/18
 */
@Deprecated
public class StartUpLoggingAppender extends AppenderBase<ILoggingEvent> {

    /**
     * 需要app启动前,就调用
     */
    private static boolean hasUse = false;
    private static ArrayList<StartUpLogHandler> lstHandler;

    protected static void beforeStartUp() {
        /*
        使用时,需要在logback中添加appender
        <appender name="startUpAppender" class="com.hup.utils.commons.start.StartUpLoggingAppender">
        </appender>
         */
        hasUse = true;
        lstHandler = new ArrayList<>();
    }

    protected static void startUpFinish() {
        if (hasUse) {
            hasUse = false;
            lstHandler.clear();
            lstHandler = null;
        }
    }

    protected static void addHandler(StartUpLogHandler handler) {
        if (!hasUse) {
            throw new IllegalArgumentException("没调用startUp()方法");
        }
        lstHandler.add(handler);
    }

    @Override
    protected void append(ILoggingEvent event) {
        if (!hasUse) {
            stop();
            return;
        }

        String msg = event.getFormattedMessage();
        //String level = event.getLevel().toString();
        //String loggerName = event.getLoggerName();
        //String threadName = event.getThreadName();
        //Throwable throwable = event.getThrowableProxy() != null ? ((ThrowableProxy) event.getThrowableProxy()).getThrowable() : null;
        Iterator<StartUpLogHandler> it = lstHandler.iterator();
        while (it.hasNext()) {
            StartUpLogHandler handler = it.next();
            if (handler.notUse()) {
                it.remove();
                continue;
            }
            handler.append(msg, event);
        }
    }

    protected interface StartUpLogHandler {
        boolean notUse();

        void append(String msg, ILoggingEvent event);
    }
}
